package org.first;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class HelloCV extends Applet implements Runnable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private CascadeClassifier faceDetector;
	private Mat m;

	public void paint(Graphics g) {
		resize(1200, 900);
		System.loadLibrary("opencv_java246");
		faceDetector = new CascadeClassifier(
				"C:/opencv/data/haarcascades/haarcascade_eye_tree_eyeglasses.xml");
		if (faceDetector.empty())
			System.exit(127);
		VideoCapture v = new VideoCapture(0);
		m = new Mat();
		v.read(m);
		new Thread(this).start();
		while (v.read(m)) {
			// detectEyes();
			BufferedImage img = new BufferedImage(m.cols(), m.rows(), BufferedImage.TYPE_3BYTE_BGR);
			byte b[] = new byte[(int) (m.cols() * m.rows() * m.elemSize())];
			Imgproc.cvtColor(m, m, Imgproc.COLOR_BGR2RGB);
			m.get(0, 0, b);
			img.getRaster().setDataElements(0, 0, m.cols(), m.rows(), b);
			g.drawImage(img, 150, 150, img.getWidth(), img.getHeight(), this);
		}
	}

	/**
	 * @param m
	 */
	private void detectEyes() {

		// Detect faces in the image.
		// MatOfRect is a special container class for Rect.
		MatOfRect faceDetections = new MatOfRect();
		faceDetector.detectMultiScale(m, faceDetections);

		System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

		// Draw a bounding box around each face.
		for (Rect rect : faceDetections.toArray()) {
			Core.rectangle(m, new Point(rect.x, rect.y),
					new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
		}
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		// super.init();
		resize(1200, 900);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			detectEyes();
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}